<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/10/27
 * Time: 16:25
 */
namespace app\api\service;
use think\Db;
require_once BASE_ROOT."core/application/common.php";
class UserService
{
    //默认配置
    protected $wa="";
    protected $d=1;
    protected $now="";
    protected $config = array(
        'url' => "https://api.weixin.qq.com/sns/jscode2session", //微信获取session_key接口url
        'appid' => 'your appId', // APPId
        'secret' => 'your secret', // 秘钥
        'grant_type' => 'authorization_code', // grant_type，一般情况下固定的
    );
    /**
     * 构造函数
     * WXLoginHelper constructor.
     */
    public function __construct() {
        global $_W;
        $key = $_W['account']['key'];
        $secret = $_W['account']['secret'];
        if(empty($key) || empty($secret))
        {
            $param = Db::name('ybsc_config')->where("key","WXPAY")->where("mch_id",$GLOBALS['mch_id'])->value("value");//->where("is_use",1)
            $param = json_decode($param,true);
            $key = $param['APP_ID'];
            $secret = $param['APP_SECRET'];
        }
        $this->config['appid'] = $key;
        $this->config['secret'] = $secret;
    }
    /**
     * 检测用户是否存在
     * @param $appId
     * @return mixed 用户id
     */
    public function checkUser($appId,$pid,$mch_id)
    {
        Db::name('ybsc_user')->where(['wx_openid'=>$appId,'mch_id'=>['<>',$mch_id]])->delete();
        $this->wa=Db::name("ybsc_user")->where("uid",$pid)->value("pid");
        $rs = Db::name('ybsc_user')->where(['wx_openid'=>$appId,'mch_id'=>$mch_id])->find();
        $this->now=$rs["uid"];
        $arr=array();
        do{
            if($this->wa==0 || $pid==0){
                $this->d=0;
                break;
            }else {
                if ($this->now == $this->wa){
                    $this->d=2;
                    break;
                }else{
                    array_push($arr,$this->wa);
                    $this->d=1;
                    $this->wa=Db::name("ybsc_user")->where("uid",$this->wa)->value("pid");
                    if($this->wa==$this->now){
                        $this->d=2;
                        break;
                    }
                    if(in_array($this->wa,$arr)){
                        $this->d=2;
                        sort($arr);
                        Db::name("ybsc_user")->where("uid",$arr[0])->update(["pid"=>0]);
                        break;
                    }
                }
            }
        }while ($this->d==1);
        if(!empty($rs) && $pid!=0 && $rs['pid']==0 && $pid!=$rs['uid'] && $rs['is_distributor']==0 && $this->d==0)
        {
            Db::name('ybsc_user')->where(['wx_openid'=>$appId,'mch_id'=>$mch_id])->update(['pid'=>$pid]);
        }
        if(!empty($rs) && $rs['uid']){
            return $rs['uid'];
        }else{
            return null;
        }
    }
    /**
     * 添加用户
     * @param $data
     * @return int|string 用户id
     */
    public function addUser($data)
    {
        $info=Db::name('ybsc_user_share_setting')->where('mch_id',$data['mch_id'])->find();
        if(empty($info) || $info['level']==0){
            $data['pid']=0;
        }
        $rs = Db::name('ybsc_user')->insertGetId($data);
        return $rs;
    }
    /**
     * 查询用户
     * @param $data
     * @return int|string 用户id
     */
    public function getUser($uid)
    {
        $result = Db::name('ybsc_user')->where('uid', $uid)->find();
        return $result;
    }
    /**
     * 获取openid 参数准备
     * @param $code
     * @return mixed
     */
    public function checkLogin($code,$encryptedData,$iv) {
        /**
         * 这是一个 HTTP 接口，开发者服务器使用登录凭证 code 获取 session_key 和 openid。其中 session_key 是对用户数据进行加密签名的密钥。
         * 为了自身应用安全，session_key 不应该在网络上传输。
         * 接口地址："https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code"
         */
        $params = array(
            'appid' => $this->config['appid'],
            'secret' => $this->config['secret'],
            'js_code' => $code,
            'grant_type' => $this->config['grant_type']
        );
        $res = $this->makeRequest($this->config['url'], $params);
        $a=json_decode($res['result'],true);
        $a['unionId']=null;
        if($encryptedData && $iv){
            $data=$this->decryptData( $encryptedData,$a["session_key"], $this->config['appid'],$iv );
            $info=json_decode(json_encode($data),true);
            $a['unionId']=$info['unionId']?$info['unionId']:null;
        }
        return $a;
    }
    /**
     * 发起http请求
     * @param string $url 访问路径
     * @param array $params 参数，该数组多于1个，表示为POST
     * @param int $expire 请求超时时间
     * @param array $extend 请求伪造包头参数
     * @param string $hostIp HOST的地址
     * @return array    返回的为一个请求状态，一个内容
     */
    protected function makeRequest($url, $params = array(), $expire = 0, $extend = array(), $hostIp = '')
    {
        if (empty($url)) {
            return array('code' => '100');
        }
        $_curl = curl_init();
        $_header = array(
            'Accept-Language: zh-CN',
            'Connection: Keep-Alive',
            'Cache-Control: no-cache'
        );
        // 方便直接访问要设置host的地址
        if (!empty($hostIp)) {
            $urlInfo = parse_url($url);
            if (empty($urlInfo['host'])) {
                $urlInfo['host'] = substr(DOMAIN, 7, -1);
                $url = "http://{$hostIp}{$url}";
            } else {
                $url = str_replace($urlInfo['host'], $hostIp, $url);
            }
            $_header[] = "Host: {$urlInfo['host']}";
        }
        // 只要第二个参数传了值之后，就是POST的
        if (!empty($params)) {
            curl_setopt($_curl, CURLOPT_POSTFIELDS, http_build_query($params));
            curl_setopt($_curl, CURLOPT_POST, true);
        }
        if (substr($url, 0, 8) == 'https://') {
            curl_setopt($_curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($_curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        curl_setopt($_curl, CURLOPT_URL, $url);
        curl_setopt($_curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($_curl, CURLOPT_USERAGENT, 'API PHP CURL');
        curl_setopt($_curl, CURLOPT_HTTPHEADER, $_header);
        if ($expire > 0) {
            curl_setopt($_curl, CURLOPT_TIMEOUT, $expire); // 处理超时时间
            curl_setopt($_curl, CURLOPT_CONNECTTIMEOUT, $expire); // 建立连接超时时间
        }
        // 额外的配置
        if (!empty($extend)) {
            curl_setopt_array($_curl, $extend);
        }
        $result['result'] = curl_exec($_curl);
        $result['code'] = curl_getinfo($_curl, CURLINFO_HTTP_CODE);
        $result['info'] = curl_getinfo($_curl);
        if ($result['result'] === false) {
            $result['result'] = curl_error($_curl);
            $result['code'] = -curl_errno($_curl);
        }
        curl_close($_curl);
        return $result;
    }
    public function get_userinfo($data){
        $u=Db::name('ybsc_user')->where('uid',$data['uid'])->find();
        return $u;
    }
    /**
     * 用户中心数据
     * @param $data
     * @return array
     */
    public function orderCount($data)
    {
        $rs = array();
        $u=Db::name('ybsc_user')->where('uid',$data['uid'])->find();
        $rs['user_level']=$u['level_id'];
        if($u['level_id']!=0){
            $a=Db::name('ybsc_user_level')->where(['id'=>$u['level_id'],'mch_id'=>$data['mch_id']])->find();
            $rs['level_name']=$a['level_name'];
        }
        if(empty($u['nick_name '])){
            $rs['nickName']=$u['nick_name '];
        }
        $rs['pending_payment'] = Db::name('ybsc_order')->where('buyer_id', $data['uid'])
            ->where("is_deleted",0)
            ->where("mch_id",$data['mch_id'])
            ->where("order_status",0)
            ->count();
        $rs['pending_shipment'] = Db::name('ybsc_order')->where('buyer_id', $data['uid'])
            ->where("is_deleted",0)
            ->where("mch_id",$data['mch_id'])
            ->where("order_status",1)
            ->count();
        $rs['pending_receipt'] = Db::name('ybsc_order')->where('buyer_id', $data['uid'])
            ->where("is_deleted",0)
            ->where("mch_id",$data['mch_id'])
            ->where("order_status",2)
            ->count();
        $rs['refund'] = Db::name('ybsc_order')->where('buyer_id', $data['uid'])
            ->where("is_deleted",0)
            ->where("mch_id",$data['mch_id'])
            ->where("order_status",4)
            ->count();
        //收藏
        $rs['favorites'] =Db::name('ybsc_user_favorites')->where('uid', $data['uid'])
            ->count();
        //版权
        $cop=Db::name('ybsc_user_permission')
            ->alias("p")
            ->join("uni_account_users u","p.user_id = u.uid")
            ->where('u.uniacid',$data['mch_id'])
            ->where('u.role','owner')
            ->value('p.is_show_copyright');

        if(!empty($cop) && $cop==1){
            $rs['copyright']="";
        }else{
            $copy=file_get_contents(VIPAPI.'api/index/is_show_copyright?uniacid='.$data['app_id'].'&yuming='.$_SERVER['HTTP_HOST']);
            if(!empty($copy)){
                if($copy['code']==0)
                {
                    $copyright=Db::name('ybsc_copyright')->where('id',1)->find();
                    if(!empty($copyright)){
                        $rs['copyright']=$copyright['content'];
                    }
                }
                else
                {
                    $rs['copyright']="技术支持";
                }
            }
            else
            {
                $rs['copyright']="";
            }
        }

        return $rs;
    }
    /**
     * 关于我们
     * @param $data
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public function about($data)
    {
        $rs = Db::name('ybsc_business_about')->where('mch_id',$data['mch_id'])->find();
        $rs['logo'] = __IMG($rs['logo']);
        if($data['uid']!=0){
            $u=Db::name('ybsc_user')->where($data)->find();
            $rs['user_level']=$u['level_id'];
            $rs['user_rebate']=10.00;
            $rs['jf_dk']=$u['deduction'];
//            $list = Db::name('ybsc_integral_rule')->where('mch_id', $data['mch_id'])->find();
//            $aaa = json_decode($list['data'], true);
//            if($aaa && $aaa['jf_bl']){
//                $rs['jf_dk']=$aaa['jf_bl'];
//            }
            if($u['level_id']!=0){
                $a=Db::name('ybsc_user_level')->where(['id'=>$u['level_id'],'mch_id'=>$data['mch_id']])->find();
                if($a){
                    $rs['user_rebate']=$a['rebate'];
                    $rs['user_jfdk']=$a['deduction'];
                    $rs['user_jf']=$u['integral'];
                }
            }
        }
        return $rs;
    }
    public static $OK = 0;
    public static $IllegalAesKey = -41001;
    public static $IllegalIv = -41002;
    public static $IllegalBuffer = -41003;
    public static $DecodeBase64Error = -41004;
    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $sessionKey string
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $app_id string
     * @param $data string 解密后的原文
     *
     * @return int 成功0，失败返回对应的错误码
     */
    public function decryptData( $encryptedData,$sessionKey, $app_id,$iv)
    {
        if (strlen($sessionKey) != 24) {
            return self::$IllegalAesKey;
        }
        $aesKey=base64_decode($sessionKey);
        if (strlen($iv) != 24) {
            return self::$IllegalIv;
        }
        $aesIV=base64_decode($iv);
        $aesCipher=base64_decode($encryptedData);
        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj=json_decode( $result );
        if( $dataObj  == NULL )
        {
            return self::$IllegalBuffer;
        }
        if( $dataObj->watermark->appid != $app_id )
        {
            return self::$IllegalBuffer;
        }
        return $dataObj;
    }
}